<%--
  Created by IntelliJ IDEA.
  User: Elle
  Date: 2022/7/9
  Time: 10:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>使用promise操作</title>
</head>
<body>
<script src="js/jquery-3.5.1.min.js"></script>
<script>
    const getJSON = function(url) {
        const promise = new Promise(function(resolve, reject){
            const handler = function() {
                if (this.readyState !== 4) {
                    return;
                }
                if (this.status === 200) {
                    resolve(this.response);
                } else {
                    reject( new Error(this.statusText)); }
            };


            const client = new XMLHttpRequest();
            client.open("GET", url);
            client.onreadystatechange = handler;
            client.responseType = "json";
            client.setRequestHeader("Accept", "application");
            client.send();
        });
        return promise;
    };

    getJSON("/posts.json").then(function(json) {
        console.log('请求成功');
    }, function(error) {
        console.error('请求失败');
    });


</script>
</body>
</html>
